package com.avalonsql.core.db.managers.impl;

import com.avalonsql.core.db.DBException;
import com.avalonsql.core.db.DBManager;
import com.avalonsql.core.db.connection.ConnectionWrapper;
import com.avalonsql.core.db.managers.api.IViewColumnsManager;
import com.avalonsql.core.db.objects.api.IRootObject;
import com.avalonsql.core.db.objects.impl.View;
import com.avalonsql.core.db.objects.impl.ViewColumn;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.TreeSet;

public class ViewColumnsManager extends ConnectionWrapperManager implements IViewColumnsManager {
    
    public ViewColumnsManager(ConnectionWrapper connectionWrapper) {
        super(connectionWrapper);
    }

    public Collection<ViewColumn> loadAll(View parent) throws DBException {
        if (parent == null) {
            throw new IllegalArgumentException("parent = null");
        }

        Collection<ViewColumn> values = new TreeSet<ViewColumn>();
        ResultSet rs = null;
        try {
            IRootObject rootObject = parent.getParent();
            rs = getDatabaseMetaData().getColumns(getCatalog(rootObject), getSchema(rootObject), parent.getName(), "%");
            while (rs.next()) {
                values.add(
                    	// todo-a
                        new ViewColumn(
                        		getStringValue(rs, "TABLE_SCHEM"), getStringValue(rs, "TABLE_CAT"),
                                getStringValue(rs, "COLUMN_NAME"), getStringValue(rs, "TYPE_NAME"), getBooleanValue(rs, "NULLABLE"), getIntValue(rs, "COLUMN_SIZE"), parent
                        )
                );
            }
        } catch (SQLException e) {
            throw new DBException(e);
        } finally {
            DBManager.closeResultSet(rs);
        }
        return values;
    }

    public void create(ViewColumn dbObject) throws DBException {
        //todo
    }

    public void update(ViewColumn dbObject) throws DBException {
        //todo
    }

    public void delete(ViewColumn dbObject) throws DBException {
        //todo
    }
}
